/*
 * Design_Assignment_1.asm
 *
 *  Created: 2/18/2014 6:41:01 PM
 *   Author: Jared Hayes
 */ 
 

 .INCLUDE "M328Pdef.inc"

.MACRO INITSTACK
	ldi r16, high(RAMEND)
	out SPH, r16
	ldi r16, low(RAMEND)
	OUT SPL, R16
.ENDMACRO
	
INITSTACK
	ldi r17, 10						// Initialize Loop Counter
	ldi r16, 140					// Start at 140
GenList:							// Generate list of 20 numbers
	ldi r19, 50						
	add r16, r19					// Add 50
	push r16						// Push number onto stack
	ldi r19, 55						
	sub r16, r19					// Subtract 55
	push r16						// Push number onto stack
	dec r17							// Decrement counter
	brne GenList					// Loop while counter /= 0

	ldi r18, 20						// Initialize loop counter
	ldi r21, 0						// Initialize div3 sum
	ldi r20, 0
	ldi r24, 0						// Initialize div5 sum
	ldi r23, 0
DivisibleLoop:
	pop r16							// Pop num from list off stack
	mov r17, r16					
	ldi r19, 210
	sub r17, r19					// Compare num to 210
	brpl ReduceNo						// If greater, reduce num by 210
	mov r17, r16
	ldi r19, 150
	sub r17, r19					// Compare num to 150
	brpl ReduceNo						// If greater, reduce num by 150
	mov r17, r16
	ldi r19, 90
	sub r17, r19					// Compare num to 90
	brpl ReduceNo						// If greater, reduce num by 90
	mov r25, r16
	mov r26, r16					// Use original num, if num < 90
	jmp DivThree

	ReduceNo:
		mov r25, r17				// Use reduced number, if num > 90
		mov r26, r17
		jmp DivThree

	DivThree:
		subi r25, 0
		breq SumThree				// Branch if num is zero
		ldi r19, 3
		sub r25, r19				// Subtract 3 from num
		brmi DivFive					// If result is negative, jump
		subi r25, 0
		brne DivThree				// Branch if num is not zero

	SumThree:						// If num is reduced to 0..
		adc r21, r16				// Add num to three's sum
		brcc DivFive				// If carry flag is clear, jump
		ldi r19, 1
		add r20, r19				// If carry flag is set, add carry

	DivFive:
		subi r26, 0
		breq SumFive				// Branch if num is not zero
		ldi r19, 5
		sub r26, r19
		brmi NextNum
		subi r26, 0
		brne DivFive

	SumFive:
		adc r24, r16
		brcc NextNum
		ldi r19, 1
		add r23, r19

	NextNum:
		dec r18						// Decrement loop counter
		brne DivisibleLoop			// Loop while counter /= 0

		ldi r22, 7


